package com.opensource.lzx.restartclient.service.impl;

import com.opensource.lzx.proto.OperationType;
import com.opensource.lzx.proto.RequestContext;
import com.opensource.lzx.proto.ServiceRequest;
import com.opensource.lzx.proto.ServiceResponse;
import com.opensource.lzx.restartclient.common.IdUtils;
import com.opensource.lzx.restartclient.netty.NettyClientTemplate;
import com.opensource.lzx.restartclient.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.Inet4Address;
import java.net.InetAddress;

/**
 * @Author: 739891618@qq.com
 * @Date: 2022-11-13 12:50:55
 * @ClassName: RegisterServiceImpl
 * @Describe: this is a ...
 */
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
    @Value("${register.linux.username}")
    private String userName;

    @Value("${register.linux.password}")
    private String password;

    @Value("${register.linux.execCommand}")
    private String execCommand;

    @Override
    public ServiceResponse register() {
        ServiceRequest.Builder requestBuilder = ServiceRequest.newBuilder();
        requestBuilder.setRequestId(IdUtils.ids());
        requestBuilder.setSshUsername(userName);
        requestBuilder.setSshPassword(password);
        requestBuilder.setExecCommand(execCommand);
        requestBuilder.setHost(buildHost());
        requestBuilder.setPort(String.valueOf(22));
        requestBuilder.setType(OperationType.REGISTER_REQUEST);
        requestBuilder.setOsName(System.getProperty("os.name"));

        RequestContext.Builder contextBuilder = RequestContext.newBuilder();
        contextBuilder.setRequest(requestBuilder);
        log.info("Ready to send msg to netty server.......");
        return NettyClientTemplate.sendMsg(contextBuilder.build(), NettyClientTemplate.getChannelKey());
    }

    private String buildHost() {
        try {
            return Inet4Address.getLocalHost().getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
